package com.heima.juc.n8;

import com.heima.juc.n2.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.*;

/**
 * @author : leimingchao
 * @date Date : 2022年02月19日 20:58
 */
@Slf4j(topic = "c.TestTimer")
public class TestTimer {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        //ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        // pool.schedule(() -> {
        //     try {
        //         log.debug("task1");
        //         int i = 1 / 0;
        //     } catch (Exception e) {
        //         log.error("error:", e);
        //     }
        // },1, TimeUnit.SECONDS);

        ExecutorService pool = Executors.newFixedThreadPool(1);
        Future<Boolean> future = pool.submit(() -> {
            log.debug("task1");
            int i = 1 / 0;
            return true;
        });

        log.debug("result:{}", future.get());
    }

    private static void method3(ScheduledExecutorService pool) {
        log.debug("start...");
        // pool.scheduleAtFixedRate(() -> {
        //     log.debug("running");
        //     Sleeper.sleep(2);
        // }, 1, 1, TimeUnit.SECONDS);

        pool.scheduleWithFixedDelay(() -> {
            log.debug("running");
            Sleeper.sleep(2);
        }, 1, 1, TimeUnit.SECONDS);
    }

    private static void method2(ScheduledExecutorService pool) {
        pool.schedule(() -> {
            log.debug("task 1");
            // Sleeper.sleep(2);
            int i = 1 / 0;
        }, 1, TimeUnit.SECONDS);

        pool.schedule(() -> {
            log.debug("task 2");
        }, 1, TimeUnit.SECONDS);
    }

    private static void method() {
        Timer timer = new Timer();
        TimerTask timerTask1 = new TimerTask() {

            @Override
            public void run() {
                log.debug("task 1");
                // Sleeper.sleep(2);
                // int i = 1 / 0;
            }
        };

        TimerTask timerTask2 = new TimerTask() {
            @Override
            public void run() {
                log.debug("task 2");
            }
        };

        log.debug("start...");
        timer.schedule(timerTask1, 1000);
        timer.schedule(timerTask2, 1000);
    }
}
